package com.ymh.git.thread.juc;

import java.sql.Connection;
import java.util.LinkedList;
import java.util.concurrent.Semaphore;

/**
 * Created by aivin on 2018/10/31.
 * 一个使用Semaphore实现的数据库连接池
 */
public class DbPoolSemaphore {

    private final static int POOL_SIZE = 10;//连接数量只有十个
    private static LinkedList<Connection> pool = new LinkedList<Connection>();//存放连接的容器
    private final Semaphore useful;//可用连接
    private final Semaphore useLess;//已用连接

    /**
     * 初始化池
     */
    static {
        for (int i = 0; i < POOL_SIZE; i++) {
            pool.addLast(SqlConnectImpl.fetchConnection());
        }
    }


    public DbPoolSemaphore() {
        this.useful = new Semaphore(POOL_SIZE);
        this.useLess = new Semaphore(0);
    }

    /**
     * 归还连接
     *
     * @param connection
     */
    public void returnConnect(Connection connection) throws InterruptedException {
        if (connection != null) {
            System.out.println("当前有" + useful.getQueueLength() + "个线程等待数据库连接！" + "可用连接数：" + useful.availablePermits());
            useLess.acquire();
            synchronized (pool) {
                pool.add(connection);
            }
            useful.release();
        }
    }

    /**
     * 从连接池中拿连接
     *
     * @return
     */
    public Connection takeConnect() throws InterruptedException {
        useful.acquire();
        Connection connection;
        synchronized (pool) {
            connection = pool.removeFirst();
        }
        useLess.release();
        return connection;
    }
}
